package com.jiayu.seckilldemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiayu.seckilldemo.execption.GlobalException;
import com.jiayu.seckilldemo.mapper.UserMapper;
import com.jiayu.seckilldemo.pojo.User;
import com.jiayu.seckilldemo.service.IUserService;
import com.jiayu.seckilldemo.utils.*;
import com.jiayu.seckilldemo.vo.LoginVo;
import com.jiayu.seckilldemo.vo.RespBean;
import com.jiayu.seckilldemo.vo.RespBeanEnum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiayu
 * @since 2022-07-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper UserMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
//        参数校验
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断是否注册
        User user = UserMapper.selectById(mobile);
        if (user == null) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        System.out.println(MD5Util.formPassToDBPass(password, user.getSalt()));
//        判断密码是否正确
        if (!MD5Util.formPassToDBPass(password, user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
//        生成Cookie
        String userTicket = UUIDUtil.uuid();
        redisTemplate.opsForValue().set("user:"+userTicket, JsonUtil.object2JsonStr(user));
        CookieUtil.setCookie(request,response,"userTicket",userTicket);
        return RespBean.success(userTicket);
    }

    /**
     * 根据cookie获取用户
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getByUserTicket(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(userTicket)){
            return null;
        }
        String userJson = (String) redisTemplate.opsForValue().get("user:"+userTicket);
        User user= JsonUtil.jsonStr2Object(userJson,User.class);
        if(user != null){
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }


}
